//
//  ZBJsonResponseSerializer.m
//  ZBDay
//
//  Created by xzb on 2018/2/6.
//  Copyright © 2018年 xzb. All rights reserved.
//

#import "ZBJsonResponseSerializer.h"
#import "ZBNetworkManager.h"

@interface ZBJsonResponseSerializer ()
@property (strong, nonatomic) NSSet *mimeTypeSet;
@end

@implementation ZBJsonResponseSerializer

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.mimeTypeSet = [NSSet setWithArray:@[
                                                 @"application/json",
                                                 @"text/json",
                                                 @"text/javascript",
                                                 @"application/x-javascript",
                                                 @"application/javascript",
                                                 ]];
    }
    return self;
}

- (id)responseObjectForResponse:(NSURLResponse *)response data:(NSData *)data error:(NSError *__autoreleasing _Nullable *)error
{
    
    ZBResponseModel *respModel = [[ZBResponseModel alloc] init];
    NSHTTPURLResponse *httpResp = (NSHTTPURLResponse *) response;
    respModel.response = httpResp;
    respModel.responseData = data;
    respModel.httpHeaders = httpResp.allHeaderFields;
    
    if (!data || data.length == 0) {
        return respModel;
    }
    
    //检查mimeType是否规范
    if (![self.mimeTypeSet containsObject:[response MIMEType]]) {
        //检查mimeType不是json 但是可以转换成json的情况
        respModel.responseJson = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
        return respModel;
    }
    respModel.responseJson = [self responseDictionaryFromData:data];
    return respModel;
}
- (NSDictionary *)responseDictionaryFromData:(NSData *)data
{
    NSError *error = nil;
    id result = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
    
    if ([result isKindOfClass:[NSDictionary class]]) {
        NSMutableDictionary *userInfo = @{}.mutableCopy;
        userInfo[@"response_dict"] = result;
        userInfo[@"response"] = result;
    }
    return result;
}
@end
